// Gizp
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css', 'html', 'json', 'svg', 'ttf']
const path = require('path')
const resolve = dir => path.join(__dirname, dir)
// Path
const glob = require('glob')

// 动态导入多页面
const getEntry = globPath => {
  let entries = {}
  let tmp = ''
  let htmls = {}

  // 读取globPath底下所有的html文件
  glob.sync(`${globPath}.html`).forEach(entry => {
    tmp = entry.split('/').splice(-3)
    htmls[tmp[1]] = entry
  })

  glob.sync(`${globPath}main.js`).forEach(entry => {
    let tmp = entry.split('/').splice(-3)
    entries[tmp[1]] = {
      entry,
      //  当前目录没有有html则以共用的public/index.html作为模板
      template: htmls[tmp[1]] ? htmls[tmp[1]] : 'index.html',
      //  以文件夹名称.html作为访问地址
      filename: tmp[1] + '.html',
      // 页面默认title
      title: '',
      chunks: ['chunk-vendors', 'chunk-common', tmp[1]]
    }
  })

  return entries
}

module.exports = {
  pages: getEntry('./src/pages/**?/*'),
  publicPath: './',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,

  configureWebpack: {
    resolve: {
      // 别名配置
      alias: {
        '@': resolve('src')
      }
    },
    plugins: [
      // Gzip压缩
      new CompressionWebpackPlugin({
        filename: '[path][base].gz',
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
        threshold: 10240, //对10K以上的数据进行压缩
        minRatio: 0.8,
        deleteOriginalAssets: false //是否删除源文件
      })
    ]
  },

  chainWebpack(config) {
    config.when(process.env.NODE_ENV !== 'development', config => {
      // 去除生产环境console
      config.optimization.minimizer('terser').tap(options => {
        options[0].terserOptions.compress.drop_console = true
        return options
      })

      // 图片处理
      config.module
        .rule('images')
        .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
        // 压缩
        .use('image-webpack-loader')
        .loader('image-webpack-loader')
        .end()
        // 转Base64
        .use('url-loader')
        .options({
          name: `img/[name].[ext]`,
          limit: 10 * 1024, //小于10kb转化为base64
          fallback: {
            loader: 'file-loader',
            options: {
              name: `img/[name].[hash:8].[ext]`
            }
          }
        })
        .end()
    })
  }
}
